package com.springboot.mongo.service;

import static org.springframework.data.mongodb.core.query.Criteria.where;

import com.springboot.common.util.SafeNullUtils;
import com.springboot.mongo.entity.UserLoginRecord;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

/**
 * 用户登陆service
 *
 * @author supu
 * @date 2019-08-27 10:11
 **/
@Service
public class UserLoginService {
    @Autowired
    private MongoTemplate mongoTemplate;

    public List<UserLoginRecord> queryUserLoginList(String userName){
        Query query = new Query(where("loginCount").gte(1));
        // 模糊查询
        Pattern pattern = Pattern.compile("^.*" + userName + ".*$", Pattern.CASE_INSENSITIVE);
        query.addCriteria(Criteria.where("userName").regex(pattern));

        return mongoTemplate.find(query, UserLoginRecord.class);
    }

    public void updateUserLogin(String userName){
        Query query = new Query();
        // 模糊查询
        Pattern pattern = Pattern.compile("^.*" + userName + ".*$", Pattern.CASE_INSENSITIVE);
        query.addCriteria(Criteria.where("userName").regex(pattern));

        List<UserLoginRecord> userLoginRecordList = mongoTemplate.find(query, UserLoginRecord.class);

        if(CollectionUtils.isEmpty(userLoginRecordList)){
            return;
        }

        List<String> ids = SafeNullUtils.safeGetStream(userLoginRecordList).map(UserLoginRecord::getId).collect(Collectors.toList());
        Query updateQuery = new Query(where("_id").in(ids));
        Update update = new Update();
        update.inc("loginCount",1);
        update.currentDate("modifyTime");

        mongoTemplate.updateMulti(updateQuery, update, UserLoginRecord.class);

        /*SafeNullUtils.safeGetStream(userLoginRecordList).forEach(userLoginRecord -> {
            Query updateQuery = new Query(where("_id").is(userLoginRecord.getId()));
            Update update = new Update();
            update.inc("loginCount",1);
            update.currentDate("modifyTime");

            mongoTemplate.updateFirst(updateQuery, update, UserLoginRecord.class);
        });*/
    }
}
